<template xmlns:el-col="http://www.w3.org/1999/html">
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px; ">
            <el-form :inline="true" ref="filters" :model="filters" size="small">
                <div v-if="!isUnitUser" style="display: inline-table;">
                    <el-form-item label="角色" prop="role_id">
                        <el-select clearable v-model="filters.role_id" clearable　placeholder="角色">
                            <el-option :key="txt" :label="txt" :value="val"
                                       v-for="(txt, val) in roles"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="姓名" prop="full_name">
                        <el-input v-model="filters.full_name"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchUsers">搜索</el-button>
                        <el-button @click="resetSearch('filters')">重置</el-button>

                    </el-form-item>
                </div>
                <el-form-item style="display: block; float: right;">
                    <el-button type="primary" @click="handleAdd" size="medium"><i class="el-icon-plus"></i>创建用户</el-button>
                </el-form-item>
            </el-form>
        </el-col>


        <el-table :data="users" style="width: 100%" v-loading="getListLoading">
            <el-table-column label="序号" type="index" width="150px"/>
            <el-table-column prop="role_id" label="角色" :formatter="getRoleNameFormatter" />
            <el-table-column prop="full_name" label="姓名" />
            <el-table-column prop="telephone" label="联系方式" />
            <el-table-column prop="organization" label="工作单位" :formatter="formatterOrg" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" plain="" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain="" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <!--分页-->
            <el-pagination
                    style="text-align: center;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-size="pager.page_size"
                    :page-sizes="pager.sizes"
                    background
                    :current-page="pager.page_current"
                    layout="prev,pager,next,sizes,total"
                    :total="pager.total">
            </el-pagination>
        </el-col>

        <el-dialog :title="dialogTitle" v-loading="dialogLoading" :visible.sync="dialogVisible"
                   :close-on-click-modal="false"
                   width="490px" :before-close="handleClose" >
            <el-form :model="userInfo" :rules="userRules" ref="userInfo" label-width="140px" class="demo-fundProduct">
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-input type="hidden" v-model="userInfo.id"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="角色分配:" prop="role_id">
                            <el-select v-model="userInfo.role_id" :disabled="getLoginUserRole.indexOf('高校') > -1 || getLoginUserRole.indexOf('教育主管部门') > -1" placeholder="请选择角色分配" @change="onRoleChange">
                                <el-option :key="txt" :label="txt" :value="val"
                                           v-for="(txt, val) in roles"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="姓名:" prop="full_name">
                            <el-input placeholder="姓名" type="text" v-model="userInfo.full_name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="电子邮箱:" prop="email">
                            <el-input placeholder="请输入电子邮箱地址" type="text" v-model="userInfo.email"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="联系方式:" prop="telephone">
                            <el-input placeholder="电话号码" type="text" v-model="userInfo.telephone"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="密码设置:" prop="content">
                            <el-input  placeholder="请输入6位以上字母和数字的组合"  type="password" v-model="userInfo.content"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="userInfo.role_name.indexOf('高校') < 0 && userInfo.role_name.indexOf('教育主管部门') < 0">
                    <el-col :span="20" :push="1">
                        <el-form-item label="工作单位:" prop="organization">
                            <el-input placeholder="请输入工作单位" type="text" v-model="userInfo.organization"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-else>
                    <div v-if="userInfo.role_name.indexOf('教育主管部门') > -1">
                        <el-col :span="20" :push="1">
                            <el-form-item label="所属教育主管部门:" prop="unit_id" >
                                <!--<el-input placeholder="请输入所属教育主管部门" :disabled="getLoginUserRole.indexOf('教育主管部门') > -1"  type="text" v-model="userInfo.unit_id"></el-input>-->
                                <el-select  filterable clearable :disabled="getLoginUserRole.indexOf('教育主管部门') > -1" @change="onUnitChange" v-model="userInfo.unit_id" placeholder="请选择主管部门">
                                    <el-option :key="item.unit_name" :label="item.unit_name" :value="item.id"
                                               v-for="(item, index) in educompetentList"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </div>
                    <div v-else>
                        <el-col :span="20" :push="1">
                            <el-form-item label="所属高校:" prop="unit_id" >
                                <el-select  filterable clearable :disabled="getLoginUserRole.indexOf('高校') > -1"  v-model="userInfo.unit_id"  @change="onUnitChange"　placeholder="请选择高校">
                                    <el-option :key="item.unit_name" :label="item.unit_name" :value="item.id"
                                               v-for="(item, index) in universityList"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </div>
                    <el-col :span="20" :push="1">
                        <el-form-item label="所在部门:" prop="belong_unit" >
                            <el-input placeholder="请输入所在部门" type="text" v-model="userInfo.belong_unit"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="职务/职称:" prop="title">
                            <el-input placeholder="请输入职务/职称" type="text" v-model="userInfo.title"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="研究方向:" prop="direction">
                            <el-input placeholder="请输入研究方向" type="text" v-model="userInfo.direction"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="地址:" prop="address">
                            <el-input placeholder="请输入地址" type="text" v-model="userInfo.address"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>

            <el-row>
                <el-col align="center">
                    <el-button type="primary" @click="submit">保 存
                    </el-button>
                    <el-button @click="handleClose">取 消</el-button>
                </el-col>
            </el-row>

        </el-dialog>

    </section>


</template>

<script>
    import * as api from '../../api/auth_api.js';
    import dict  from '../../common/js/dict'
    import {userName, password, date_of_birth} from "../../common/js/checkFields";

    export default {
        data() {
            var validName = (rule, value, callback) => {
                let reg = /^[a-zA-Z\u4e00-\u9fa5]{1,10}$/;
                if (!reg.test(value)) {
                    callback(new Error('10位以内的汉字或字母'));
                } else {
                    callback();
                }
            };
            var validTelephone = (rule, value, callback) => {
                let reg = /^1[3|4|5|7|8][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确的手机号码'));
                } else {
                    callback();
                }
            };
            var validPassword = (rule,value,callback) => {
                if(!this.userRules.content[0].required) { return callback() }
                if (!rule.required && value === '') { callback() }
                if(!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)){
                    callback(new Error("密码要求长度6-20位的字母与数字组合"));
                }else{
                    callback();
                }
            }
            var validEmail = (rule,value,callback) => {
                let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
                if(!reg.test(value)){
                    callback(new Error("请输入正确邮箱格式"));
                }else{
                    callback();
                }
            }
            return {
                dict: dict,
                //分页设置
                pager: {
                    sizes: [10, 20, 30, 40, 50],
                    total: 0,
                    page_size: 10,
                    page_current: 1
                },
                users: [],
                roles: {},
                unitList: [],
                filters: {
                    role_id: '',
                    full_name: ''
                },
                //dialog
                getListLoading:true,
                isUniversity:false,
                dialogVisible: false
                ,dialogLoading: false
                ,dialogTitle: '创建用户'
                ,userInfo: {
                    id: '',
                    role_id: "",
                    role_name: "",
                    full_name: "",
                    telephone: "",
                    content: "",
                    unit_name:'',
                    unit_id:'',
                    organization:"",
                    title:'',
                    email:'',
                    direction:'',
                    address:''

                },
                loginUserInfo:this.$store.getters.getUserInfo
                ,universityList:[]
                ,userRules: {
                    role_id: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                    full_name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                        {validator: validName, trigger: 'blur'}
                    ],
                    belong_unit: [
                        {required: true, message: '请输入所在部门', trigger: 'blur'},
                        {validator: validName, trigger: 'blur'}
                    ],
                    telephone: [
                        {required: true, message: '请输入联系方式', trigger: 'blur'},
                        {validator: validTelephone, trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入电子邮箱', trigger: 'blur'},
                        {min: 0, max: 30, message: '不超过30个字符', trigger: 'change'}
                    ],
                    content: [
                        // {required: true, message: '请设置密码', trigger: 'change'},
                        // {required: true, message: '请设置密码',validator: validPassword, trigger:'blur'}
                        {required: false, message: '请设置密码', trigger:'blur'},
                        { validator: validPassword, trigger: 'blur'}
                    ],
                    organization: [
                        {min: 0, max: 50, message: '不超过50个字符', trigger: 'change'}
                    ],
                    unit_id: [
                        {required: true, message: '请选择高校', trigger: 'blur'},
                    ],
                    title: [
                        {min: 0, max: 50, message: '不超过50个字符', trigger: 'change'}
                    ],
                    direction: [
                        {min: 0, max: 50, message: '不超过50个字符', trigger: 'change'}
                    ],
                    address: [
                        {min: 0, max: 50, message: '不超过50个字符', trigger: 'change'}
                    ],
                }
            }
        },
        created(){
            this.getUniversity()
        },
        methods: {
            /*getLabel(id,Arr){//这个vId也就是value值

                let obj = {};
                obj = this.userList.find((item)=>{//这里的userList就是上面遍历的数据源
                    return item.id === id;//筛选出匹配数据
                });

                return obj.name
            },*/
            onUnitChange(id){
                if(!id){
                    this.userInfo.unit_name= ''
                    this.userInfo.belong_college= ''
                    return false
                }
                let obj = {};
                if(this.isUniversity){
                    obj = this.universityList.find((item)=>{//这里的userList就是上面遍历的数据源
                        return item.id === id;//筛选出匹配数据
                    })
                } else{
                    obj = this.educompetentList.find((item)=>{//这里的userList就是上面遍历的数据源
                        return item.id === id;//筛选出匹配数据
                    })
                }
               this.userInfo.unit_name= obj.unit_name
               this.userInfo.belong_college= obj.unit_name
            },

            onRoleChange(id){
                let obj = this.roles
                  for(var p in obj){
                    if (p === id) {
                        this.userInfo.role_name = obj[p]
                        if(obj[p] == '高校')
                            this.isUniversity = true
                        else
                            this.isUniversity = false
                    }
                }

            },
            getUniversity(){
                api.universityNonPaged().then(res =>{
                    let tempData = JSON.parse(res.data.datas), university = [], educompetent = []
                    tempData.map(item => {
                        if(item.type == 2)
                            educompetent.push(item)
                        else
                            university.push(item)
                    })
                    this.universityList = university
                    this.educompetentList = educompetent
                })
            },
            //分页page_size发生改变
            handleSizeChange(val) {
                this.pager.page_current = 1;
                this.pager.page_size = val;
                this.getUsers();
            },
            //分页page_current发生改变
            handleCurrentChange(val) {
                this.pager.page_current = val;
                this.getUsers();
            },
            searchUsers() {
                this.pager.page_current = 1;
                this.getUsers();
            },
            resetSearch(formName){
                this.$refs[formName].resetFields();
                this.searchUsers();
            },
            getUsers() {
                this.getListLoading = true
                if(this.isUnitUser){
                    //获取学校用户列表
                    let param = {
                        condition:{
                            unit_id: this.loginUserInfo.unit_id
                        },
                        page_size:1000,
                        page_current:1

                    }//获取用户
                    api.userInfoOnPage(param).then(res => {
                        this.getListLoading = false
                        if (res.data.status === 200) {
                            let datas = JSON.parse(res.data.datas);
                            this.users = datas.items;
                            this.pager.total = datas.total;
                        } else {
                            this.$message.error(res.data.status + " " + res.data.msg);
                        }
                    })
                }else{
                    let condition = {
                        // user_name: this.filters.user_name,
                        full_name: this.filters.full_name,
                        // manager_unit_name: this.filters.manager_unit_name,
                        role_id: this.filters.role_id,
                    };
                    let params = {
                        page_size: this.pager.page_size,
                        page_current: this.pager.page_current,
                        condition: condition
                    };

                    api.userList(params).then((res) => {
                        this.getListLoading = false
                        if (res.data.status === 200) {
                            let datas = JSON.parse(res.data.datas);
                            this.users = datas.items;
                            this.pager.total = datas.total;
                        } else {
                            this.$message.error(res.data.status + " " + res.data.msg);
                        }
                    });
                }
            },

            getRoles() {
                api.userRoleList().then((res) => {
                    if (res.data.status === 200) {
                        let datas = JSON.parse(res.data.datas);
                        datas.forEach((item) => {
                            this.roles[item.id] = item.role;
                        });
                        this.getUsers();
                    } else {
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }
                });
            },

            // ========================================= add start ===============================================
            handleAdd() {
                this.dialogTitle = '创建用户';
                this.dialogVisible = true;
                if(this.$refs['userInfo']) this.$refs['userInfo'].clearValidate();
                if(this.isUnitUser)  {
                    this.userInfo.role_id = this.loginUserInfo.role_id;
                    this.userInfo.role_name = this.loginUserInfo.role_name;
                    this.userInfo.organization = this.loginUserInfo.organization;
                    this.userInfo.unit_name = this.loginUserInfo.unit_name;
                    this.userInfo.unit_id = this.loginUserInfo.unit_id;
                }
                this.userRules.content[0].required = true; //新增的时候密码必填
            },
            submit() {
                this.$refs['userInfo'].validate((valid) => {
                    if (valid) {
                        this.dialogLoading = true;  //显示loading
                        let params = {
                            full_name: this.userInfo.full_name,
                            user_name: this.userInfo.telephone,
                            content: this.userInfo.content,
                            role_id: this.userInfo.role_id,
                            telephone: this.userInfo.telephone,
                            organization: this.userInfo.organization,
                            title: this.userInfo.title,
                            email: this.userInfo.email,
                            direction: this.userInfo.direction,
                            address: this.userInfo.address,
                            role_name:this.userInfo.role_name,
                            unit_name:this.userInfo.unit_name,
                            belong_college:this.userInfo.belong_college,
                            belong_unit:this.userInfo.belong_unit,
                            unit_id:this.userInfo.unit_id
                        };
                        if(this.userInfo.id == ''){
                            api.addUser(params).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '添加成功!'
                                    });
                                    this.userInfo = {
                                        id: '',
                                        role_id: "",
                                        role_name: "",
                                        full_name: "",
                                        telephone: "",
                                        content: "",
                                        unit_name:'',
                                        unit_id:'',
                                        organization:"",
                                        title:'',
                                        email:'',
                                        direction:'',
                                        belong_college:'',
                                        belong_unit:'',
                                        address:''
                                    }
                                    this.dialogVisible = false;
                                    this.searchUsers();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                }
                            });
                        }else{
                            params.id = this.userInfo.id;
                            api.updateUser(params).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '编辑成功!'
                                    });
                                    this.userInfo = {
                                        id: '',
                                        role_id: "",
                                        role_name: "",
                                        full_name: "",
                                        telephone: "",
                                        content: "",
                                        unit_name:'',
                                        unit_id:'',
                                        organization:"",
                                        title:'',
                                        email:'',
                                        direction:'',
                                        belong_college:'',
                                        belong_unit:'',
                                        address:''
                                    }
                                    this.dialogVisible = false;
                                    this.searchUsers();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                }
                            });
                        }
                        this.handleClose();

                    }
                });
            },
            handleClose() {

                    this.$refs['userInfo'].resetFields();
                    this.$refs['userInfo'].clearValidate();
                this.userInfo = {
                    id: '',
                    role_id: "",
                    role_name: "",
                    full_name: "",
                    telephone: "",
                    content: "",
                    unit_name:'',
                    unit_id:'',
                    organization:"",
                    title:'',
                    email:'',
                    direction:'',
                    belong_college:'',
                    belong_unit:'',
                    address:''
                }
                this.dialogVisible = false;



            },
            // ========================================= add end ===============================================
            // ========================================= edit start ===============================================
            handleEdit(row) {
                this.userRules.content[0].required = false; //修改的时候密码可以为空
                this.dialogTitle = '编辑用户';
                this.dialogVisible = true;
              // /  this.dialogLoading = true;  //显示loading
              //   let params = {"id": row.id};
                 this.userInfo = Object.assign({},row)
                if(this.userInfo.role_name == '高校')
                    this.isUniversity = true
                else
                    this.isUniversity = false
              /*  api.userInfo(params).then((res) => {
                    if (res.data.status === 200) {
                        this.dialogLoading = false;  //显示loading
                        this.userInfo = JSON.parse(res.data.datas);
                    } else {
                        this.$message({
                            type: 'info',
                            message: '系统繁忙'
                        });
                    }
                });*/
            },
            // ========================================= edit end ===============================================

            handleDelete(row) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {"id": row.id};
                    api.deleteUser(params).then((res) => {
                        if (res.data.status === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getUsers();
                        } else {
                            this.$message({
                                type: 'info',
                                message: result.msg
                            });
                        }
                    });

                });
            }

            ,getRoleNameFormatter(row,column){
                if(column){
                    return this.roles[row[column.property]];
                }
                return this.roles[row];
            },
            formatterOrg(row){
                if(row.role_name.indexOf('高校') > -1 || row.role_name.indexOf('教育主管部门') > -1){
                    return row.unit_name
                }  else {
                    return row.organization
                }
            },
           initData(){
               clearInterval(this.timer)
               if (this.loginUserInfo.role_name) {
                   this.getRoles()
               } else {
                   this.timer = setInterval(this.initData, 100)
               }
           }

        },
        computed:{
            getLoginUserRole(){
                this.loginUserInfo = this.$store.getters.getUserInfo
                let login_user_role_name = this.$store.getters.getUserInfo.role_name || ''
                return login_user_role_name
            },
            isUnitUser(){
                let login_user_role_name = this.$store.getters.getUserInfo.role_name || ''
                if(login_user_role_name.indexOf('高校') == -1 && login_user_role_name.indexOf('教育主管部门') == -1 ){
                    return false
                } else {
                    return true
                }
            }
        },
        mounted() {
            this.$nextTick(function () {
                this.initData()
            })
        }

    }
</script>
<style>

</style>
